package com.yatb.trac.controller.validator;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.EmailValidator;
import org.springframework.util.ClassUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.yatb.trac.pojo.Utenti;
import com.yatb.trac.pojo.wrappers.UtentiView;
import com.yatb.trac.util.TracSetupUtil;

public class ModificaUtenteValidator implements Validator {

	public boolean supports(Class<?> arg0) {
		return ClassUtils.isAssignable(UtentiView.class, arg0);
	}

	public void validate(Object command, Errors errors) {

	}
	
	public void validateRequestParams(HttpServletRequest request,Object target,Errors errors){
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String repeatPassword = request.getParameter("repeatPassword");
		String email = ((UtentiView)target).getUtenti().getEmail();
		EmailValidator emailValidator = EmailValidator.getInstance();
		if(!emailValidator.isValid(email)){
			errors.rejectValue("utenti.email", "", "Email inserita non valida!");
		}
		List myErrors = new ArrayList();
		if(oldPassword.trim().equals("")){
			request.setAttribute("oldPasswordError", "Inserire la vecchia password");
			myErrors.add("oldPassword");
			errors.reject("ciccio", "");
		}
		if(newPassword.trim().equals("")){
			request.setAttribute("newPasswordError", "Inserire la nuova password");
			myErrors.add("newPassword");
			errors.reject("ciccio", "");
		}
		if(repeatPassword.trim().equals("")){
			request.setAttribute("repeatPasswordError", "Inserire la nuova password una seconda volta");
			myErrors.add("repeatPassword");
			errors.reject("ciccio", "");
		}
		if(myErrors.isEmpty()){
			try {
				oldPassword = new TracSetupUtil().md5(((UtentiView)target).getUtenti().getUsername()+oldPassword);
			} catch (GeneralSecurityException e) {
			}
			if(!oldPassword.equals(((UtentiView)target).getUtenti().getPassword())){
				request.setAttribute("oldPasswordError", "La vecchia password non corrisponde a quella attuale");
				errors.reject("ciccio", "");
			}
			if(!repeatPassword.equals(newPassword)){
				request.setAttribute("repeatPasswordError", "Le due password non corrispondono");
				errors.reject("ciccio", "");
			}
		}
		
		
		
	}
	
	

}
